import { categories, works, studioInfo, photographers } from "./data";

const STORAGE_KEY = "USE_MOCK_API";
let bookings = [];
let bookingSequence = 1;

export const mockSwitch = {
  isEnabled() {
    const stored = readStoredFlag();
    if (stored !== null) {
      return stored;
    }
    return getDefaultEnvFlag();
  },
  setEnabled(flag) {
    const next = !!flag;
    if (typeof uni !== "undefined" && uni.setStorageSync) {
      uni.setStorageSync(STORAGE_KEY, next ? "true" : "false");
    }
    return next;
  }
};

export function handleMockRequest(options) {
  const { url = "", method = "GET", data = {} } = options || {};
  const upperMethod = method.toUpperCase();
  const path = getPath(url);
  const query = parseQuery(url);

  if (upperMethod === "GET" && path === "/api/categories") {
    return wrapSuccess(sortByOrder(categories));
  }

  if (upperMethod === "GET" && path === "/api/works") {
    const categoryId = query.categoryId ?? data.categoryId;
    const filtered = categoryId
      ? works.filter(item => item.categoryId === categoryId)
      : works;
    return wrapSuccess(filtered.map(attachPhotographerSnapshot));
  }

  if (upperMethod === "GET" && path.startsWith("/api/works/")) {
    const id = path.replace("/api/works/", "");
    const found = works.find(item => item.id === id);
    if (!found) {
      return wrapNotFound();
    }
    return wrapSuccess(attachPhotographerDetail(found));
  }

  if (upperMethod === "GET" && path === "/api/studio") {
    return wrapSuccess({
      ...studioInfo,
      photographers
    });
  }

  if (upperMethod === "GET" && path === "/api/photographers") {
    return wrapSuccess(photographers);
  }

  if (upperMethod === "POST" && path === "/api/bookings") {
    const payload = { ...data };
    const required = ["workId", "customerName", "contactPhone", "preferredDate"];
    const missing = required.filter(key => !payload[key]);
    if (missing.length) {
      return wrapValidationFailed(`缺少必要字段: ${missing.join(", ")}`);
    }
    const bookingId = `BK${String(bookingSequence++).padStart(5, "0")}`;
    const booking = {
      bookingId,
      status: "created",
      createdAt: Date.now(),
      ...payload
    };
    bookings = [booking, ...bookings].slice(0, 50);
    return wrapSuccess({
      bookingId
    }, "预约提交成功，我们会尽快与您联系");
  }

  return wrapNotImplemented(path, upperMethod);
}

export function resetMockBookings() {
  bookings = [];
  bookingSequence = 1;
}

function readStoredFlag() {
  if (typeof uni === "undefined" || !uni.getStorageSync) return null;
  const value = uni.getStorageSync(STORAGE_KEY);
  if (value === "true") return true;
  if (value === "false") return false;
  return null;
}

function getDefaultEnvFlag() {
  if (typeof import.meta !== "undefined" && import.meta.env && typeof import.meta.env.VITE_USE_MOCK !== "undefined") {
    return import.meta.env.VITE_USE_MOCK === "true";
  }
  // 默认关闭mock，使用真实后端接口
  return false;
}

function getPath(url) {
  const baseRemoved = url.replace(/^https?:\/\/[^/]+/i, "");
  return baseRemoved.split("?")[0];
}

function parseQuery(url) {
  const queryString = url.split("?")[1] || "";
  if (!queryString) {
    return {};
  }
  return queryString.split("&").reduce((acc, pair) => {
    if (!pair) return acc;
    const [rawKey, rawValue = ""] = pair.split("=");
    const key = decodeURIComponent(rawKey || "");
    if (!key) return acc;
    acc[key] = decodeURIComponent(rawValue);
    return acc;
  }, {});
}

function wrapSuccess(data, message = "success") {
  return Promise.resolve({
    code: 0, // 与后端保持一致，成功时返回 0
    msg: message,
    data
  });
}

function wrapNotFound() {
  return Promise.resolve({
    code: 404,
    msg: "未找到相关作品",
    data: null
  });
}

function wrapValidationFailed(message) {
  return Promise.resolve({
    code: 422,
    msg: message,
    data: null
  });
}

function wrapNotImplemented(path, method) {
  return Promise.resolve({
    code: 501,
    msg: `${method} ${path} 尚未实现`,
    data: null
  });
}

function sortByOrder(list) {
  return [...list].sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
}

function attachPhotographerSnapshot(work) {
  const photographer = photographers.find(item => item.id === work.photographerId);
  if (!photographer) {
    return work;
  }
  return {
    ...work,
    photographer: {
      id: photographer.id,
      name: photographer.name,
      avatarUrl: photographer.avatarUrl
    }
  };
}

function attachPhotographerDetail(work) {
  const snapshot = attachPhotographerSnapshot(work);
  if (!snapshot.photographer) {
    return snapshot;
  }
  const full = photographers.find(item => item.id === snapshot.photographer.id);
  if (!full) {
    return snapshot;
  }
  return {
    ...snapshot,
    photographer: full
  };
}
